//
//  NetworkService.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/1/30.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import Alamofire
import XCGLogger

typealias NetworkFailure = (_ code:Int, _ msg:String) -> Void
typealias NetworkSuccess = (_ response:[String: Any]?, _ data:Any?) -> Void
//typealias NetworkSuccess = (_ response:[String: Any]?) -> Void

fileprivate let k_result_msg_key = "msg"
fileprivate let k_result_code_key = "code"
fileprivate let k_result_success_code = 0

let kTimeoutInterval: TimeInterval = 5

let shareNetwok = NetworkService()
class NetworkService {
    
    var sessionManager: SessionManager
    
    init() {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = kTimeoutInterval
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        
        self.sessionManager = SessionManager(configuration: configuration)
        
    }
    
    @discardableResult //忽略返回值
    public func send(_ path:String,
                     method: HTTPMethod = .get,
                     parameter:[String:Any]? = nil,
                     success:NetworkSuccess?,
                     failure:NetworkFailure?) -> DataRequest? {
        
        
        
        let url = Config.default.baseAPI + path
        let headers  = ["Content-Type":"application/json"]
        
        var encoding:ParameterEncoding
        if  method == .post {
            encoding = JSONEncoding.default
        }
        else {
            encoding = URLEncoding.default
        }
        
        
        let para = getParameters(parameter)
        
        let requrest = self.sessionManager.request(url,
                                                   method: method,
                                                   parameters: para,
                                                   encoding: encoding,
                                                   headers: headers).responseJSON { (dataResponse) in
            
            //成功
            if dataResponse.result.isSuccess {
                if let json = dataResponse.result.value as? Parameters {
                    
                    XCGLogger.default.debug(json)
                    let resultJson = json
                    var code:Int?
                    
                    //解析code
                    code = resultJson[k_result_code_key] as? Int
                    
                    //成功
                    if k_result_success_code == code {
                    
                        let data = resultJson["data"]
                        success?(resultJson, data)
                    }
                    else {
                        var msg = ""
                        //解析msg
                        if let result_msg = String.lsf_parse(resultJson[k_result_msg_key]) {
                            msg = result_msg
                        }
                        else {
                            msg = "msg is nil"
                        }
                        
                        failure?(code ?? -1, msg)
                    }
                }
            }
                
                //失败
            else {
                let msg = dataResponse.result.error?.localizedDescription ?? "网络请求失败"
                let code = dataResponse.response?.statusCode ?? 0
                
                failure?(code, msg)
            }
        }
        
        
        return requrest
    }
    
    ///拼接参数
    func getParameters(_ parameters:Parameters?) -> Parameters {
        var dictionary:Parameters
        if parameters != nil {
            dictionary = parameters!
        }
        else {
            dictionary = Parameters.init()
        }
        
        if let token = AccountStorage.default.account.token {
            dictionary["token"] = token
        }
        
        if let uid = AccountStorage.default.account.uid {
            dictionary["uid"] = uid
        }
        
        
        return dictionary
    }
    
    @discardableResult //忽略返回值
    static public func get(_ path:String,
                    parameter:[String:Any]? = nil,
                    success:NetworkSuccess?,
                    failure:NetworkFailure?) -> DataRequest?  {
        return shareNetwok.send(path, method: .get, parameter: parameter, success: success, failure: failure)
    }
    
    
    @discardableResult //忽略返回值
    static public func post(_ path:String,
                     parameter:[String:Any]? = nil,
                     success:NetworkSuccess?,
                     failure:NetworkFailure?) -> DataRequest?  {
        return shareNetwok.send(path, method: .post, parameter: parameter, success: success, failure: failure)
    }
}
